<template>
  <div class="maintenance-info q-mt-md">
    <div class="plan-title q-mb-md">
      {{ title }}
    </div>
    <!-- form 表单 -->
    <div class="row justify-between">
        <yz-input
          v-model="queryParams.maintenanceType"
          inputType="select"
          :rules="[0]"
          style="width:400px"
          class="margin-r-30"
          @input="onDelStep"
          :options="maintenanceTypeOptions"
          title="保养类型"
        ></yz-input>
        <div class="form-item margin-r-30">
          <span class="text-red">*</span><span class="form-name" style="padding-right: 6px">保养开始日期:</span>
          <date-picker
            v-model="queryParams.startDate"
            type="date"
            :range="false"
            :clearable="false"
            :editable="false"
            :disabled-date="disabledBeforeToday"
            @change="queryParams.assignedAdvanceDays = 0"
            style="width:330px"
            :rules="val => (val && val.length > 0) || '不能为空'"
            format="YYYY-MM-DD"
            placeholder="请选择保养开始日期"/>
        </div>
        <div class="row ">
            <yz-input
              v-model="queryParams.assignedAdvanceDays"
              :rules="[0]"
              :options="orderTimeOptions"
              class="q-mr-sm"
              inputType="select"
              style="width:300px"
              title="派单时间"
            ></yz-input>
          <div>
            <date-picker
              v-model="queryParams.assignedDate"
              format="HH:mm"
              value-type="format"
              type="time"
              placeholder="选择时间"
              style="width:178px"
            ></date-picker>
          </div>
        </div>
    </div>
    <div class="row justify-between">
        <yz-input
                  v-model="queryParams.recurRuleFreq"
                  inputType="select"
                  style="width:400px"
                  class="margin-r-30"
                  @click.native="onChangeRecurRuleFreq"
                  :options="maintenanceCycleOptions"
                  title="循环周期"
                  ></yz-input>

      <div class="row items-start" style="margin-right: 26px;">
        <div class="row q-ml-sm q-mr-sm">
          <div class="q-mt-sm">
            <span class="text-red">*</span><span class="font-size-16">保养人员:</span>
          </div>
          <div class="">
            <q-radio
              v-model="queryParams.assignedCriteria"
              @input="onSelectClaimWay"
              :val="1"
              label="当班操作工"
            />
            <q-radio
              v-model="queryParams.assignedCriteria"
              @input="onSelectClaimWay"
              :val="2"
              label="指定人员"
            />
          </div>
        </div>
        <div class="">
          <select-tooltip v-if="queryParams.assignedCriteria === 1"
                          v-model="queryParams.assignedShiftId"
                          isShowAll
                          style="width: 170px"
                          :multiple="false"
                          :options="shiftsOptions"></select-tooltip>
          <div v-else>
            <sel-person
              style="width: 150px"
              :person="queryParams.assignedOperatorName"
              :userList="queryParams"
              @change="selectPer"
              title="添加保养人员"
            ></sel-person>
          </div>
        </div>
      </div>

      <div class="row" v-if="queryParams.assignedCriteria === 2">
          <div>
            <q-input
              v-model="queryParams.estimatedTime"
              dense
              emit-value
              map-options
              style="width: 290px"
              placeholder=""
              :rules="[
              val => val && val.length > 0 || '不能为空',
              val => val > 0 || '不能小于等于 0 ',
              val => val <= 999 || '不能大于 999 ',
              val => /^\d+(\.\d)?$/.test(val) || '最多一位小数' ]"
              outlined
            >
              <template v-slot:before>
                <label
                  class="text-right name form-name label-width"
                  style="width: 108px"
                >
                  <span class="text-red">*</span>计划保养时长<span>:</span>
                </label>
              </template>
            </q-input>
          </div>
          <div>
            <yz-input
              v-model="queryParams.estimatedTimeUnit"
              :options="planTimeOptions"
              inputType="select"
              style="height: 32px; width: 190px"
            ></yz-input>
          </div>
      </div>
      <div v-else class="row" style="width: 460px"></div>
    </div>
<!--    日循环限制 -->
    <div class="flex" v-if="queryParams.recurRuleFreq === 'DAILY'">
        <yz-input
          v-model="queryParams.pausedFrequency"
          @click.native="onChangeFrequency"
          inputType="select"
          style="width:240px"
          :options="limitMaintenanceOptions"
          title="限制保养"></yz-input>
          <yz-input       v-if="queryParams.pausedFrequency  === 'WEEKLY'"
                          v-model="queryParams.pausedDays"
                          inputType="select"
                          multiple
                          :rules="[9]"
                          style="height: 32px; width: 160px"
                          :options="allWeekOptions"
                          ></yz-input>
          <yz-input       v-if="queryParams.pausedFrequency  === 'MONTHLY'"
                          v-model="queryParams.pausedMonthDays"
                          inputType="select"
                          :rules="[9]"
                          multiple
                          style="height: 32px; width: 160px"
                          :options="allMonthOptions"
                          ></yz-input>
      </div>
    <!--    月循环限制 -->
    <div class="flex" v-else-if="queryParams.recurRuleFreq === 'MONTHLY'">
        <yz-input
          v-model="queryParams.pausedMonths"
          inputType="select"
          multiple
          style="width:240px"
          :options="outMonthOptions"
          title="限制保养"></yz-input>
      </div>
    <q-separator  class="qa-line"/>
    <div class="flex justify-between q-mb-md q-mt-sm">
      <div class="flex">
        <div class="text-right name form-name label-width">
          <span class="text-red">*</span>保养项目<span>:</span>
        </div>
        <!-- 添加项目名称 -->
        <div class="step handle q-ml-md" v-if="queryParams.programId">
            <span class="txt ellipsis">
              {{queryParams.maintenanceProgramName}}
            </span>
            <q-icon @click.stop="onDelStep" class="close fr cursor-pointer" name="iconfont icontubiao-89" />
        </div>
      </div>
      <div>
            <q-btn class="qa-btn margin-r-10"
                   outline
                   color="primary"
                   :disable="queryParams.programId !== undefined && queryParams.programId !== ''"
                   @click="onAddProgram">添加项目</q-btn>
      </div>
    </div>
    <!-- table -->
    <div class="page-content">
              <q-table :data="tableData"
                       :columns="columns"
                       row-key="id"
                       class="myTable scroll stick-to-top"
                       :loading="isTableLoading"
                       :pagination.sync="pagination"
                       style="height: 400px; margin: 0"
                       :hide-bottom="tableData.length > 0"
                       color="primary">
              <template v-slot:body-cell-index="props">
                <q-td>
                  {{props.row.__index + 1}}
                </q-td>
              </template>
              <template v-slot:body-cell-criteria="props">
                <q-td>
                  {{props.row.criteria | toHorizontalLine }}
                </q-td>
              </template>
          </q-table>
      </div>
      <slot name="part"></slot>
      <!-- remark -->
      <div class="q-mb-md q-mt-md">
            <yz-input inputType="textarea" style="margin-left: -45px" v-model="queryParams.remark" title="备注"  :maxlength="200"/>
      </div>
      <maintenance-program-dialog
          :show="isShowMaintenanceProgramDialog"
          :maintenanceType="queryParams.maintenanceType"
          @close="isShowMaintenanceProgramDialog = false"
          @submit="onSelectProgram"/>
  </div>
</template>
<script>
import _ from 'lodash'
import moment from 'moment'
import maintenanceProgramDialog from './maintenance-program-dialog'
import selPerson from './maintenance-sel-person.vue'
import { mapGetters } from 'vuex'
import {
  getShiftsList
} from 'src/boot/maintenance/maintenance-plan'
import { getMaintenaceProgramsById } from 'src/boot/maintenance/maintenance-item'
const disabledBeforeToday = (date) => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  return date < today
}
export default {
  name: 'maintenance-info',
  components: { maintenanceProgramDialog, selPerson },
  props: {
    title: String
  },
  data () {
    return {
      queryParams: {
        maintenanceType: 1, // 保养类型
        startDate: new Date(new Date().setHours(0, 0, 0, 0)),
        assignedHours: '', // 派单小时数
        assignedMinutes: '', // 派单分钟数
        assignedAdvanceDays: 0, // 提前派单天数 0:当天
        assignedDate: '',
        assignedCriteria: 1, // 指派方式
        assignedOperatorIds: [], // 指派人员id
        assignedOperatorName: '', // 指派人员name
        assignedShiftId: 'all', // 班制ID
        estimatedTime: '', // 计划保养时长
        estimatedTimeUnit: 1, // 时长单位
        pausedFrequency: 'none', // 限制保养周期
        remark: '',
        programId: '', // 项目id
        maintenanceProgramName: '', // 项目名称
        pausedDays: [], // 限制保养日期时间
        pausedMonthDays: [], // 限制保养日期时间 日子
        pausedMonths: [], // 限制保养月循环
        recurRuleFreq: '', // 循环周期
        assignedShiftsModeId: '' // 班制模式
      },
      shiftsOptions: [], // 班次
      isTableLoading: false,
      isShowMaintenanceProgramDialog: false,
      tableData: [],
      pagination: {
        rowsPerPage: 0
      },
      columns: [
        { name: 'index', label: '序号', align: 'left', field: 'index' },
        { name: 'contentName', label: '项目内容', align: 'left', field: 'contentName' },
        { name: 'criteria', label: '判断基准', align: 'left', field: 'criteria' }
      ],
      disabledBeforeToday: disabledBeforeToday
    }
  },
  computed: {
    //  保养周期枚举
    maintenanceCycleOptions () {
      return this.$getEnum(this.Enums.MAINTENANCE_CYCLE)
    },
    //  保养类型枚举
    maintenanceTypeOptions () {
      return this.$getEnum(this.Enums.MAINTENANCE_TYPE)
    },
    //  计划时长
    planTimeOptions () {
      return this.$getEnum(this.Enums.PLAN_TIME_UNIT)
    },
    // 限制保养
    limitMaintenanceOptions () {
      return this.$getEnum(this.Enums.LIMIT_MAINTENANCE_UNIT)
    },
    // 派单时间
    orderTimeOptions () {
      const startDay = moment(new Date(new Date().setHours(0, 0, 0, 0)))
      const endDay = moment(this.queryParams.startDate)
      let diff = endDay.diff(startDay, 'days')
      const num = diff < 0 || _.isNaN(diff) ? 1 : diff + 1
      const member = this.$getEnum(this.Enums.ORDER_TIME)
      return member.reduce((arr, item, index) => {
        item.disable = index + 1 > num
        arr.push(item)
        return arr
      }, [])
    },
    // 星期
    allWeekOptions () {
      return this.$getEnum(this.Enums.ALL_WEEK)
    },
    allMonthOptions () {
      let arr = []
      for (let i = 1; i <= 31; i++) {
        arr.push({
          label: i,
          value: i
        })
      }
      return arr
    },
    outMonthOptions () {
      let arr = []
      for (let i = 1; i <= 12; i++) {
        arr.push({
          label: `${i}月`,
          value: i
        })
      }
      return arr
    },
    ...mapGetters({
      'maintainItemContent': 'maintenance/maintainItemContent'
    })
  },
  methods: {
    refreshData () {
      // 刷新数据
      Object.assign(this.queryParams, this.$options.data.call(this).queryParams)
      this.shiftsOptions = []
      this.tableData = []
    },
    // edit 初始化数据
    initData (val) {
      this.queryParams = Object.assign(this.queryParams, val)
      this.queryParams.assignedShiftId = 'all'
      this.queryParams.assignedOperatorName = this.queryParams.assignedOperatorNameList && this.queryParams.assignedOperatorNameList.join()
      this.queryParams.assignedDate = this.setAssignedDate(val)
      this.queryParams.startDate = new Date(moment(val.startDate))
      this.queryParams.estimatedTime = !_.isNil(val.estimatedTime) ? String(val.estimatedTime) : ''
      this.queryParams.pausedFrequency = _.isEmpty(val.pausedFrequency) ? 'none' : val.pausedFrequency
      setTimeout(() => {
        this.queryParams.pausedMonthDays = val.pausedMonthDays
        this.queryParams.assignedAdvanceDays = this.orderTimeOptions.map(v => v.value).includes(val.assignedAdvanceDays) ? val.assignedAdvanceDays : this.orderTimeOptions[0].value
        this.queryParams.pausedDays = val.pausedDays
        this.queryParams.maintenanceProgramName = val.maintenanceProgramName
        this.queryParams.programId = val.programId
        this.tableData = val.maintenanceItems
      })
    },
    setAssignedDate ({ assignedHours, assignedMinutes }) {
      const hours = String(assignedHours).length === 1 ? `0${assignedHours}` : assignedHours
      const minutes = String(assignedMinutes).length === 1 ? `0${assignedMinutes}` : assignedMinutes
      return `${hours}:${minutes}`
    },
    // 拼接数据
    setData () {
      let params = {
        ...this.queryParams
      }
      if (this.queryParams.assignedDate) {
        const dateList = this.queryParams.assignedDate.split(':')
        params['assignedHours'] = dateList[0]
        params['assignedMinutes'] = dateList[1]
      }
      params['startDate'] = this.$utils.setDateOSI(this.queryParams['startDate'], false)
      params.assignedShiftId = this.queryParams.assignedShiftId === 'all' ? 0 : this.queryParams.assignedShiftId
      params.assignedShiftsModeId = this.queryParams.assignedCriteria === 1 ? this.queryParams.assignedShiftsModeId : ''
      params.pausedFrequency = this.queryParams.pausedFrequency === 'none' ? '' : this.queryParams.pausedFrequency
      if (this.queryParams.assignedCriteria === 1) {
        params = _.omit(params, ['estimatedTime', 'estimatedTimeUnit'])
      }
      return params
    },
    onSelectClaimWay (val) {
      this.queryParams.assignedShiftId = 'all'
      this.queryParams.assignedOperatorIds = []
      this.queryParams.assignedOperatorName = ''
    },
    onSelectProgram (val) {
      this.queryParams.maintenanceProgramName = _.get(val[0], 'name', '')
      this.queryParams.programId = _.get(val[0], 'id', '')
      this.isShowMaintenanceProgramDialog = false
      this.getProgram()
    },
    // 删除保养项目
    onDelStep () {
      this.queryParams.maintenanceProgramName = ''
      this.queryParams.programId = ''
      this.tableData = []
    },
    // 切换限制保养
    onChangeFrequency () {
      this.queryParams.pausedDays = []
      this.queryParams.pausedMonthDays = []
    },
    // 切换循环周期
    onChangeRecurRuleFreq () {
      this.queryParams.pausedMonths = []
      this.queryParams.pausedFrequency = 'none'
      this.onChangeFrequency()
    },
    onAddProgram () {
      this.isShowMaintenanceProgramDialog = true
    },
    selectPer (data) {
      this.queryParams.assignedOperatorIds = _.map(data, 'id')
      this.queryParams.assignedOperatorName = _.get(data, 'name', '')
    },
    // 根据项目id 获取项目内容
    getProgram () {
      this.isTableLoading = true
      getMaintenaceProgramsById(this.queryParams.programId).then((result) => {
        const ret = result.data
        this.tableData = ret.items
        this.isTableLoading = false
      }).catch((err) => {
        this.isTableLoading = false
        console.log(err)
      })
    },
    // 获取班次
    // 编辑的时候会传入班次shiftsId 直接回显在页面上,
    getShiftsList (workShopId, shiftsId = null) {
      if (!workShopId) {
        this.queryParams.assignedShiftId = 'all'
        this.shiftsOptions = []
        return
      }
      getShiftsList(workShopId).then((result) => {
        this.shiftsOptions = result.data.map(v => {
          const item = v
          item.label = v.name
          item.value = v.id
          return item
        })
        this.queryParams.assignedShiftsModeId = _.get(result.data[0], 'shiftsModeId', '')
        // 编辑的时候回显班次
        if (!_.isNil(shiftsId)) {
          this.queryParams.assignedShiftId = shiftsId === 0 ? 'all' : this.shiftsOptions.map(v => v.value).includes(shiftsId) ? shiftsId : 'all'
        }
      }).catch((err) => {
        this.shiftsOptions = []
        console.log(err)
      })
    }
  },
  mounted () {}
}
</script>
<style lang="scss" scoped>
.maintenance-info{
    .step{
        display: inline-block;
        padding: 0 10px;
        min-width:100px;
        height:32px;
        line-height: 32px;
        color: #fff;
        background: #F7B82D;
        box-shadow:0px 1px 5px 0px rgba(0, 0, 0, 0.15);
        border-radius:6px;
        .txt{
          display: inline-block;
          width: 100px;
          vertical-align: middle;
        }
        .close{
          margin-top: 8px;
          opacity: 0.6;
        }
      }
      .f-width{
        width: 30%
      }
      .margin-r-30{
        margin-right: 1%;
      }
}

</style>
